@tool
extends ProgressBar


class_name ColorFlatProgressBar


## 背景颜色
@export var bg_color: Color = Color.GRAY
## 不同分段的颜色
@export var percent_colors: Array[Color] = []
## 最后填充的颜色
@export var fill_color: Color = Color.GREEN
## 边框颜色
@export var bd_color: Color = Color.WHITE
## 边框宽度
@export var border_width: int = 0


var border_rate: float = 0


func _ready() -> void:
    var bg: StyleBoxFlat = StyleBoxFlat.new()
    bg.bg_color = bg_color
    bg.border_width_left = border_width
    bg.border_width_right = border_width
    bg.border_width_top = border_width
    bg.border_width_bottom = border_width
    bg.border_color = bd_color

    var fill: StyleBoxFlat = StyleBoxFlat.new()
    fill.bg_color = fill_color
    fill.border_width_left = border_width
    fill.border_width_right = 0 if value < max_value else border_width
    fill.border_width_right = border_width
    fill.border_width_top = border_width
    fill.border_width_bottom = border_width
    fill.border_color = bd_color

    set("theme_override_styles/background", bg)
    set("theme_override_styles/fill", fill)
    show_percentage = false

    border_rate = 1.0 - 2.0 * border_width / size.x

func _value_changed(new_value: float) -> void:
    if border_width > 0:
        var is_hide_border: bool = border_rate >= (new_value / max_value) if border_rate >= step else new_value < max_value
        var fillbox: StyleBoxFlat = get("theme_override_styles/fill") as StyleBoxFlat
        fillbox.border_width_right = 0 if is_hide_border else border_width
    if percent_colors.size() < 1:
        return
    var percent_step: float = max_value / (percent_colors.size() + 1)
    var percent_index: int = int(new_value / percent_step)
    var color: Color = percent_colors[percent_index] if percent_index < percent_colors.size() else fill_color
    var fill: StyleBoxFlat = get("theme_override_styles/fill") as StyleBoxFlat
    fill.bg_color = color
